package org.example;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

import static org.apache.poi.ss.util.CellUtil.createCell;

public class PhoneNumberProcessor {

    private static final Map<String, String[]> PHONE_LOCATION_MAP = new HashMap<>();

    private static final boolean DEBUG = true;  // 调试开关

    private static void debugLog(String message) {
        if (DEBUG) {
            System.out.println("[DEBUG] " + message);
        }
    }

    static {
        loadPhoneSegmentData();
    }

    private static void loadPhoneSegmentData() {
        try {
            String[] pathsToTry = {
                    "./phone_segment.csv",
                    "src/main/resources/phone_segment.csv",
                    "/phone_segment.csv"
            };

            InputStream is = null;
            for (String path : pathsToTry) {
                File file = new File(path);
                if (file.exists()) {
                    System.out.println("找到数据库文件: " + file.getAbsolutePath());
                    is = new FileInputStream(file);
                    break;
                }

                // 从JAR内部资源加载
                is = PhoneNumberProcessor.class.getResourceAsStream(path);
                if (is != null) {
                    System.out.println("从JAR资源加载数据库文件: " + path);
                    break;
                }
            }

            if (is == null) {
                throw new FileNotFoundException("未找到phone_segment.csv文件");
            }

            try (BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    // 使用CSV安全解析（兼容引号和逗号）
                    String[] parts = line.split(",(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)", -1);
                    if (parts.length >= 6) {
                        String segment = parts[1].replaceAll("\"", "").trim();
                        String[] location = {
                                parts[2].replaceAll("\"", "").trim(), // 省份
                                parts[3].replaceAll("\"", "").trim(), // 城市
                                parts[4].replaceAll("\"", "").trim(), // 运营商
                                parts[5].replaceAll("\"", "").trim()  // 新增：区号
                        };
                        PHONE_LOCATION_MAP.put(segment, location);
                    }
                }
                System.out.println("成功加载号段数据量: " + PHONE_LOCATION_MAP.size());
                if (PHONE_LOCATION_MAP.isEmpty()) {
                    System.err.println("警告：号段数据库为空！");
                }
            }
        } catch (Exception e) {
            System.err.println("数据库加载失败原因: " + e.getMessage());
            e.printStackTrace();
            System.exit(1);
        }
    }

    private static String[] getLocationInfo(String phone) {
        String cleaned = phone.replaceAll("[^0-9]", "");
        if (cleaned.length() >= 11) {
            String segment = cleaned.substring(0, 7);
            String[] location = PHONE_LOCATION_MAP.get(segment);
            return location != null ? location : new String[]{"未知", "未知", "未知"};
        }
        return new String[]{"无效号码", "", ""};
    }




    public static void processExcel(String filePath) throws Exception {
        try (InputStream is = new FileInputStream(filePath);
             Workbook workbook = WorkbookFactory.create(is)) {

            Sheet sheet = workbook.getSheetAt(0);
            for (Row row : sheet) {
                Cell phoneCell = row.getCell(0);
                if (phoneCell == null) continue;

                String phone = getCellValue(phoneCell);
                String[] location = getLocationInfo(phone);

                // 创建或获取三列
                createCell(row, 1, location[0]); // 省份
                createCell(row, 2, location[1]); // 城市
                createCell(row, 3, location[2]); // 运营商
                createCell(row, 4, location[3]); // 新增：区号
            }

            // 自动调整列宽
            for (int i = 0; i < 5; i++) {
                sheet.autoSizeColumn(i);
            }

            try (OutputStream os = new FileOutputStream(filePath)) {
                workbook.write(os);
            }
        }
    }

    private static void createCell(Row row, int columnIdx, String value) {
        Cell cell = row.getCell(columnIdx);
        if (cell == null) {
            cell = row.createCell(columnIdx);
        }
        cell.setCellValue(value);
    }

    private static String getCellValue(Cell cell) {
        if (cell.getCellType() == CellType.NUMERIC) {
            return String.format("%.0f", cell.getNumericCellValue());
        }
        return cell.getStringCellValue();
    }

    public static void processFile(String filePath) throws Exception {
        if (filePath.toLowerCase().endsWith(".txt")) {
            processTextFile(filePath);
        } else if (filePath.toLowerCase().matches(".*\\.xls[x]?")) {
            processExcel(filePath);
        } else {
            throw new IllegalArgumentException("不支持的文件类型");
        }
    }

    private static void processTextFile(String filePath) throws Exception {
        File tempFile = new File(filePath + ".tmp");
        try (BufferedReader reader = new BufferedReader(new FileReader(filePath));
             BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile))) {

            String line;
            while ((line = reader.readLine()) != null) {
                String processedLine = processTextLine(line);
                writer.write(processedLine);
                writer.newLine();
            }
        }

        // 用临时文件替换原始文件
        Files.move(tempFile.toPath(), new File(filePath).toPath(),
                StandardCopyOption.REPLACE_EXISTING,
                StandardCopyOption.ATOMIC_MOVE);
    }

    private static String processTextLine(String line) {
        String[] originalParts = line.split("\\|", -1); // 保留所有空值
        String phonePart = originalParts[0].trim();
        String[] otherParts = originalParts.length > 1 ?
                line.substring(originalParts[0].length()+1).split("\\|", -1) : // 保留后续所有内容
                new String[0];

        // 提取电话号码
        String[] phoneComponents = phonePart.split("\\s+", 2);
        String phone = phoneComponents[0];
        String[] location = getLocationInfo(phone);

        // 构建新行结构
        StringBuilder sb = new StringBuilder();
        // 原始号码部分
        sb.append(phonePart.replaceFirst(phone, phone)).append("|");
        // 归属地信息
        sb.append(String.join("|", location));
        // 其他原有内容
        if (otherParts.length > 0) {
            sb.append("|").append(String.join("|", otherParts));
        }

        // 清理多余分隔符
        String result = sb.toString()
                .replaceAll("\\|{2,}", "|") // 替换多个连续竖线
                .replaceAll("^\\|", "")     // 去除行首竖线
                .replaceAll("\\|$", "");    // 去除行尾竖线

        // 最终格式：原始号码部分|省份|城市|运营商|其他内容
        return result;
    }

    public static void test() throws Exception {
        Scanner scanner = new Scanner(System.in);
        System.out.print("请输入文件路径（支持.xls/.xlsx/.txt）: ");
        String filePath = scanner.nextLine().trim();

        File inputFile = new File(filePath);
        if (!inputFile.exists()) {
            System.err.println("错误：文件不存在！");
            System.exit(1);
        }


        String ext = filePath.substring(filePath.lastIndexOf(".")).toLowerCase();
        if (!ext.matches("\\.(xls|xlsx|txt)")) {
            System.err.println("错误：仅支持.xls、.xlsx和.txt文件！");
            System.exit(1);
        }

        if (filePath.toLowerCase().endsWith(".xls") ||
                filePath.toLowerCase().endsWith(".xlsx")) {
            if (!checkExcelFormat(filePath)) {
                System.err.println("错误：Excel文件格式异常，请确认是否为有效Excel文件");
                System.exit(1);
            }
        }

        long startTime = System.currentTimeMillis();
        processFile(filePath);
        long endTime = System.currentTimeMillis();

        System.out.println("处理完成！耗时: " + formatTime(endTime - startTime));
//        scanner.close();
    }


    public static void main(String[] args) throws Exception {
        Scanner scanner = new Scanner(System.in);
        System.out.print("请输入文件路径（支持.xls/.xlsx/.txt）: ");
        String filePath = scanner.nextLine().trim();

        File inputFile = new File(filePath);
        if (!inputFile.exists()) {
            System.err.println("错误：文件不存在！");
            System.exit(1);
        }


        String ext = filePath.substring(filePath.lastIndexOf(".")).toLowerCase();
        if (!ext.matches("\\.(xls|xlsx|txt)")) {
            System.err.println("错误：仅支持.xls、.xlsx和.txt文件！");
            System.exit(1);
        }

        if (filePath.toLowerCase().endsWith(".xls") ||
                filePath.toLowerCase().endsWith(".xlsx")) {
            if (!checkExcelFormat(filePath)) {
                System.err.println("错误：Excel文件格式异常，请确认是否为有效Excel文件");
                System.exit(1);
            }
        }

        long startTime = System.currentTimeMillis();
        processFile(filePath);
        long endTime = System.currentTimeMillis();

        System.out.println("处理完成！耗时: " + formatTime(endTime - startTime));
        scanner.close();
    }

    private static boolean checkExcelFormat(String filePath) {
        try (InputStream is = new FileInputStream(filePath);
             Workbook workbook = WorkbookFactory.create(is)) {
            return workbook.getNumberOfSheets() > 0;
        } catch (Exception e) {
            return false;
        }
    }

    private static String formatTime(long milliseconds) {
        long minutes = milliseconds / (60 * 1000);
        long seconds = (milliseconds % (60 * 1000)) / 1000;
        return String.format("%02d分%02d秒", minutes, seconds);
    }
}
